package com.nlx.notes.support.filter;

import com.nlx.notes.support.context.UserHolder;
import com.nlx.notes.support.interceptor.CachedBodyHttpServletRequest;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.UUID;

@Slf4j
@Component
public class TokenFilter implements Filter {

    private static final String TRACE_ID = "traceId";



    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            String traceId = UUID.randomUUID().toString();;
            MDC.put(TRACE_ID, traceId);
//            log.info("进入过滤器，url -> {}" ,request.getRemoteAddr());
//            chain.doFilter(request, response);
            if (!(request instanceof HttpServletRequest)) {
                chain.doFilter(request, response);
                return;
            }
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            // 包装 request
            CachedBodyHttpServletRequest wrappedRequest = new CachedBodyHttpServletRequest(httpServletRequest);

            chain.doFilter(wrappedRequest, response);


        } finally {
            // 无论是否异常都执行，确保清理 ThreadLocal
            UserHolder.removeUserContext();
        }
    }

}
